#include <cstdio>

#include <fstream>
#include <string>

#include "Config.h"
#include "utils.h"

using namespace std;
using namespace session_mgr;

namespace session_mgr
{
    Config& getConfig()
    {
        return Config::instance;
    }
}

Config Config::instance;

void Config::load(const char* path) throw (char const*)
{
    ifstream file(path);
    
    if(!file.is_open())
        throw "Cannot open config file.";
    
    string line;
    
    if(!getline(file, line))
        throw "Empty config file.";
    
    unsigned listenPort;
    if(sscanf(line.c_str(), "listen%u", &listenPort) != 1)
        throw "The first line of config file should be a \"listen\" directive.";
    this->listenPort = listenPort;
    
    while(getline(file, line))
    {
        if(line.empty())
            continue;
        unsigned a, b, c, d, port, cards;
        if(sscanf(line.c_str(), "%u.%u.%u.%u:%u%u", &a, &b, &c, &d, &port, &cards) !=6)
        {
            clients.clear();
            throw "Client line format error. Expected format: xxx.xxx.xxx.xxx:port card_count";
        }
        ClientConnection client;
        client.ipv4addr = addr(a, b, c, d);
        client.port = port;
        client.card_count = cards;
        clients.push_back(client);
    }
    if(clients.empty())
        throw "No clients in the config file.";
}

std::vector< ClientConnection > const& Config::getClients() const
{
    return clients;
}

uint16_t Config::getListenPort() const
{
    return listenPort;
}
